<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserProfile extends CI_Controller {

	function __construct()
	{
		parent::__construct();
	}

	function index()
	{
		/*$session =array(
		     'session_id'    => random hash,
		     'ip_address'    => $this->input->ip_address(),
		     'user_agent'    => 'string - user agent data',
		     'last_activity' => timestamp
		);*/
		$this->load->view('createprofile_view');
	}
	
	function login(){
		$this->load->model('Users');
		//$username="ss@dd.c";
		//$password="asd";
		$username=$this->input->post('email');
		$password=$this->input->post('password');
		$l = $this->Users->validate($username,$password);
		//echo $l;
		if($l){
			$loggedin = array(
				'username' => $username,
				'logged_in' => true
			);
			$this->session->set_userdata($loggedin);
			//echo "Login Successful". $l;
                        redirect('home');
		}
		else{
			$data["result"]="Login Failed";
			$this->load->view('createprofile_view',$data);
		}
		
	}
	function register()
	{
		$first_name=$this->input->post('fname');
		$last_name=$this->input->post('lname');
		$email=$this->input->post('remail');
		$validate_email=$this->input->post('remailvalid');
		$password=$this->input->post('rpassword');
		$confirm=$this->input->post('rpasswordconfirm');
		$birthday=$this->input->post('birthday');
		//validation first
		/*$valid=true;
		if($email!=$validate_email){
			$result="E-Mails does not Match\n";
			$valid=false;
		}
		if($password!=$confirm){
			$result +="Passwords does not Match\n";
			$valid=false;
		}
		*/
		$this->load->library('form_validation');

		$this->form_validation->set_rules('fname', 'First Name', 'required');
		$this->form_validation->set_rules('lname', 'Last Name', 'required');
		$this->form_validation->set_rules('remail', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('remailvalid', 'Email Confirmation', 'required|valid_email|matches[remail]');
		$this->form_validation->set_rules('rpassword', 'Password', 'required');
		$this->form_validation->set_rules('rpasswordconfirm', 'Password Confirmation', 'required|matches[rpassword]');
		$this->form_validation->set_rules('birthday', 'Birthday', 'required');

		if ($this->form_validation->run() == FALSE)
		{
			$data["result"]=validation_errors();
			$this->load->view('createprofile_view',$data);

		}
		else
		{
			
			$this->load->model('Users');
			$now=date('Y-m-d H:i:s');
			$result="";
			if($this->Users->isRegistered($email)){
				$result="This email is already exist.";
			}
			else
				if( $this->Users->create_profile($first_name,$last_name,$email,$password,$birthday,$now))
					$result="User Registred Successfully";
			
			if ($this->input->post('ajax')) {
				
			}
			else{
				$data["result"]=$result;
				$this->load->view('createprofile_view',$data);
			}
		}
		
		
		
	}

	function logout(){
		$data = array('username' => '', 'logged_in' => '');
		$this->session->unset_userdata($data);
		//echo "logged Out";
                redirect('userprofile');
	}

        function searchFriend()
	{

            // To DO
            // parameter must be passed by browser ..
            // input $param which is current user email (my email) .

            $param = $_POST['useremail'] ;

            //echo $param;



            $data['records']  = $this->friendsIAdded($param);
            $data['records2']  = $this->friendsAddedMe($param)  ;

            //echo print_r($data['records']);

            //$this->table->
           // load the page
           $this->load->view('friendsList_view', $data);

	}

        //mousa and hussam
        function addFriend()
        {

            $sitId=$_POST['sitId'];
            $friendEmail=$_POST['FriendEmail'];
		$this->load->model('Situation');
		$query=$this->Situation->addFriend($sitId,$friendEmail);
                //echo $query;
                //getting the situation name
                    $sitInfo=$this->Situation->getSitInfo($sitId);
                    foreach($sitInfo->result_array()as $row)
                    {

                        $sitName=$row['name'];
                    }
                    //getting situation owner information
                    $ownerInfo=$this->Situation->getSitOwnerInfo($sitId);
                    foreach($ownerInfo->result_array() as $row)
                    {
                        $fname=$row['firstName'];
                        $lname=$row['lastName'];
                        $email=$row['email'];
                    }
                    $data = /*array(
                        'state'=>*/ $query;
			//);

                  //$json=json_encode($data);
                  //echo $json;
                  //echo $data;
                    $config=array (

                       /* 'protocol' => 'smtp',
                        'smtp_host' => 'ssl://smtp.googlemail.com',
                        'smtp_port' => 465,
                        'smtp_user' => '',
                        'smtp_pass'=> ''*/
                    );
                if($query=='0')//not registered
                {

                    /*$this->load->library('email',$config);
                    $this->email->set_newline("\r\n ");
                    $this->email->from('',$fname.' '.$lname);
                    $this->email->to('');

                    $this->email->subject('Invitation from your friend '.$fname.' '.$lname);
                    $this->email->message('you have an invaitation from your friend.'.$fname.' '.$lname.' to visit XPages \n Regards\n XPAGES');
                    $this->email->send();
                    echo $this->email->print_debugger();*/
                    echo '0';
                }
                else if($query=='1') // added
                {
                   /*$this->load->library('email',$config);

                    $this->email->from('swe966@gmail.com',$fname.' '.lname);
                    $this->email->to('swe966@gmail.com');

                    $this->email->subject('Invitation from your friend '.$fname.' '.lname);
                    $this->email->message('you have an invaitation from your friend.'.$fname.' '.lname.' to visit '.$sitName. ' \n Regards\n XPAGES');

                    $this->email->send();

                    echo $this->email->print_debugger();*/
                    echo '1';


                }
                else if($query=='2')// alreaday friend
                {
                    echo '2';
                }

        }

        function deleteFriend()
        {

            $sit_id=$_POST['sit_id']; // ID of the situation that the frined will be deleted from
            $friend_email=$_POST['friend_email'];

            $this->load->model('Situation');
            $query=$this->Situation->deleteFriend($sit_id,$friend_email);

            if($query==null)
            {
                echo false;
            }
            else
            {
                echo true;
            }



        }

        function showInformation()
            {
                $email=$_POST['email'];
                $this->load->model('Users');
                $query =$this->Users->getInformation($email);

                foreach ($query->result_array() as $row)
		{
			$emil=$row['email'];
			$date=$row['dateOfBirth'];
			$fName=$row['firstName'];
                        $lName=$row['lastName'];
                        $password=$row['password'];
                        $registrationDate=$row['registrationDate'];
                        $notif=$row['notifiable'];

		}

		$data = array(
			'email'=> $email,
                        'dateOfBirth'=> $date,
                        'firstName'=> $fName,
                        'lastName'=> $lName,
                        'password'=> $password,
                        'registrationDate'=> $registrationDate,
                        'notif'=>$notif

			);
                $json=json_encode($data);
		echo $json; // this is the infortaion of the user to display it
            }

            function updateProfileNOP ()
            {


                $email=$_POST['email'];
                $fname=$_POST['fname'];
                $lname=$_POST['lname'];
                $date=$_POST['dateOfBirth'];
                $notif=$_POST['notif'];

             //loading the model
                $this->load->model('Users');

            // putting the data to an array to send it to the database
                    $data= array(
                        'firstName'=>$fname,
                        'lastName'=>$lname,
                        'dateOfBirth'=>$date,
                        'notifiable'=>$notif
                    );


                       print_r($data);
                    $query= $this->Users->setInformationNoP($email,$data);
            }

            function updateProfileWP()
            {

                $email=$_POST['email'];
                $fname=$_POST['fname'];
                $lname=$_POST['lname'];
                $password_old=$_POST['password_old'];

                $password_new=$_POST['password_new'];

                $date=$_POST['dateOfBirth'];
                $notif=$_POST['notif'];






             //loading the model
                $this->load->model('Users');

            //checking the password
                $result=  $this->Users->getPassword($email);
                foreach ($result->result() as $row)
                {
                    $result_pass=$row->password;
                }
                //echo md5($password_new);
                if($result_pass== md5($password_old)) // passwords mach                {
                {

            // putting the data to an array to send it to the database
                    $data= array(
                        'firstName'=>$fname,
                        'lastName'=>$lname,
                        'password'=>md5($password_new),
                        'dateOfBirth'=>$date,
                        'notifiable'=>$notif,
                    );

                    $query= $this->Users->setInformationWP($email,$data);
                    echo true;
                }
                else
                {
                    echo false; // passwords do not match
                }
            }
           // this function will find friends I added them as friends ...
        // input $param which is current user email (my email) .

        function friendsIAdded($param)
        {

                // To DO
                // parameter must be passed by browser ..
//                $param = "aq@example.com" ;       // sample one for time being





                $this->load->library('pagination');
		$this->load->library('table');


		$config['base_url'] = 'http://localhost:8888/friendsList/index.php/friendsList/index';


                // setting the offset and number of rows per page ..
                $offset = $this->uri->segment(3, 0)  ;
                $num = 10 ;

                // for debuging
                //   echo 'offset <br>' ; echo $offset ;


                // this query without limits
                $q1 = "SELECT firstName   , lastName   , friendEmail   , name  , SituationID


                      FROM  situationfriendlist as sl , situation as s , userprofile u

                      WHERE s.ID =  sl.SituationID and sl.friendEmail = u.email and sl.SituationID in

                    (
                    select id
                    from situation
                    where UserProfile_email = '$param'
                    )

                    order by SituationID

                    " ;

                // second query with limits
                $q2 = "SELECT firstName   , lastName   , friendEmail   , name  , SituationID


                      FROM  situationfriendlist as sl , situation as s , userprofile u

                      WHERE s.ID =  sl.SituationID and sl.friendEmail = u.email and sl.SituationID in

                    (
                    select id
                    from situation
                    where UserProfile_email = '$param'
                    )

                    order by SituationID
                    LIMIT $offset , $num
                    " ;




                // initialize paging settings
                $config['total_rows'] = $this->db->query($q1) ->num_rows();
                $config['per_page'] = 10;
		$config['num_links'] = 20;
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';

                $this->pagination->initialize($config);

//               // For debuging
//                echo $config['total_rows'];




                $table = $this->db->query($q2);
               // $data['records'] = $table;

                return $table ;
            }



            // this function will find friends that added ME as theirs friend ..
            // input $param which is current user email (my email) .
        function friendsAddedMe($param)
        {

                // To DO
                // parameter must be passed by browser ..
   //             $param = "aq@example.com" ;       // sample one for time being // my email





                $this->load->library('pagination');
		$this->load->library('table');


		$config['base_url'] = 'http://localhost:8888/friendsList/index.php/friendsList/index';


                // setting the offset and number of rows per page ..
                $offset = $this->uri->segment(3, 0)  ;
                $num = 10 ;

                // for debuging
                //   echo 'offset <br>' ; echo $offset ;


                // this query without limits
                $q1 = "
                    SELECT firstName   , lastName   , email   , name  , ID

                    FROM  situation as s , userprofile u

                    WHERE s.UserProfile_email = u.email

                    and

                    s.ID in
                    (
                    select SituationID
                    from situationfriendlist
                    where friendEmail = '$param'
                    )
                    order by ID

                    " ;

                // second query with limits
                $q2 = "
SELECT firstName   , lastName   , email   , name  , ID

                    FROM  situation as s , userprofile u

                    WHERE s.UserProfile_email = u.email

                    and

                    s.ID in
                    (
                    select SituationID
                    from situationfriendlist
                    where friendEmail = '$param'
                    )
                    order by ID
                    LIMIT $offset , $num
                    " ;




                // initialize paging settings
                $config['total_rows2'] = $this->db->query($q1) ->num_rows();
                $config['per_page2'] = 10;
		$config['num_links2'] = 20;
		$config['full_tag_open2'] = '<div id="pagination2">';
		$config['full_tag_close2'] = '</div>';

                $this->pagination->initialize($config);

//               // For debuging
//                echo $config['total_rows'];




                $table = $this->db->query($q2);
               // $data['records2'] = $table;

                return $table ;
            }
}